/*
 * @Author: Cenven
 * @Date: 2020-12-07 11:07:37
 * @Description: 北京泓深教育发展有限公司
 * @Descripttion: 
 * @version: @Lastest
 * @LastEditTime: 2021-01-22 16:28:29
 * @CopyRight: 北京泓深教育发展有限公司
 */
export const dataURLtoFile = (dataurl, filename) => {
  //将base64转换为文件
  var arr = dataurl.split(","),
    mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], filename + "." + mime.split("/")[1], { type: mime });
};

export const fileToBase64 = function(file, callback) {
  var r = new FileReader();
  var base64 = "";
  // 转成base64
  r.onload = function() {
    base64 = r.result;
    callback(base64);
  };
  r.readAsDataURL(file); //转成Base64格式
};

export const blobToDataURL = function(blob, callback) {
  let a = new FileReader();
  a.onload = function(e) {
    callback(e.target.result);
  };
  a.readAsDataURL(blob);
};
export const dataURLtoBlob = function(dataurl) {
  var arr = dataurl.split(","),
    mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new Blob([u8arr], { type: mime });
};

export const getBase64Image = img => {
  var canvas = document.createElement("canvas");
  canvas.width = img.width;
  canvas.height = img.height;
  var ctx = canvas.getContext("2d");
  ctx.drawImage(img, 0, 0, img.width, img.height);
  var ext = img.src.substring(img.src.lastIndexOf(".") + 1).toLowerCase();
  var dataURL = canvas.toDataURL("image/" + ext);
  return {
    dataURL: dataURL,
    type: "image/" + ext
  };
};

export const absoluteUrlToBase64 = fileUrl => {
  return new Promise((res, rej) => {
    var image = new Image();
    image.crossOrigin = "";
    image.src = fileUrl;
    image.onload = () => {
      var base64 = getBase64Image(image);
      res(base64);
    };
  }).then();
};
